from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
import os
# 在文件顶部添加
import sys
sys.path.append(r'd:\AiPro\english')  # 添加项目根目录到Python路径

# 修改原有导入
from ocr_handwriting_python3_demo.ocr import process_image

#from ocr_handwriting_python3_demo.ocr_handwriting_python3x_demo.ocr import getHeader, getBody

from ecc_service import correct_essay
import configparser

app = Flask(__name__, template_folder='../webapp')
CORS(app)

UPLOAD_FOLDER = r'd:\AiPro\english\uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/upload', methods=['POST'])
def handle_upload():
    try:
        # 处理试卷模板和学生作业
        template = request.files['template']
        homework = request.files['homework']
        
        # 保存文件
        template_path = os.path.join(UPLOAD_FOLDER, template.filename)
        homework_path = os.path.join(UPLOAD_FOLDER, homework.filename)
        template.save(template_path)
        homework.save(homework_path)
        
        # 调用OCR服务
        # 修改OCR调用方式
        ocr_result = process_image(homework_path)
        
        # 调用作文批改
        # 在文件顶部添加
        import configparser
        
        # 在app初始化后添加配置读取
        config = configparser.ConfigParser()
        config.read(r'd:\AiPro\english\config.ini')
        
        # 修改原有调用部分
        correction = correct_essay(
            config.get('Tencent', 'secret_id'),
            config.get('Tencent', 'secret_key'),
            ocr_result
        )
        
        return jsonify({
            'status': 'success',
            'ocr_text': ocr_result,
            'correction': correction.to_dict()
        })
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)